import { moneyFormatCol, nanoid10 } from '@/utils';
import { MonthEnum } from '@/utils/enum';
import { Selection, Summary, TotalItem } from 'devextreme-react/data-grid';
import React, { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useModel } from 'umi';
import { DevGrid } from '~/public/cpas-ui';
import { columnsDataM } from './columnData';
import './index.less';
// import { Button } from "devextreme-react";
import { msgInfo } from '@/utils/msg';
import { UserOutlined } from '@ant-design/icons';
import { TreeSelectKeyContext } from '../../index';
import { getFYFXList } from './service';
import TableLoading from './TableLoading';

const DetailsTableComponent = React.forwardRef((props: any, ref: any) => {
  const { leftParamsObj } = useContext<any>(TreeSelectKeyContext);

  const {
    generateMonth,
    selMonthDataEnd,
    selMonthDataStart,
    selDataValue,
    selDefaultValue,
    selectTreeNode,
    valueRadio,
    hiddenEmptyData
  } = leftParamsObj;
  const { initialState } = useModel('@@initialState');
  // const { username } = initialState?.curUser;
  const { zcbfName, dbname } = initialState?.curPart;
  const devGridRef = useRef<any>(null);
  const [tempColumnsData, setTempColumnsData] = useState<any[]>(columnsDataM);
  const [devBox, setDevBox] = useState<any>(nanoid10());

  const [selArrData, setSelArrData] = useState<any>([]);
  const [valueCheckbox, setValueCheckbox] = useState(true);
  const [dataSourceArr, setDataSourceArr] = useState<any>([]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);

  const [rowClicking, setRowClicking] = useState<boolean>(false);

  const changeTempColumnsData = (tempData: any[]) => {
    setDevBox(nanoid10());
    setSelArrData(tempData);
    let tempA: any[] = tempData.map((item) => {
      return {
        dataField: `${item >= 10 ? '' : '0'}${item}`,
        dataType: 'number',
        dataTypeCustom: 'money-number',
        caption: `${MonthEnum[item]}月`,
        width: 120,
        alignment: 'right',
        format: '#,##0.00',
        editorOptions: {
          format: { type: 'decimal', currency: 'CNY', precision: 2 },
        },
      };
    });
    // 创建新的数组 newColumns
    let newColumns = [];
    // 添加 columnsDataM 的第一个元素
    newColumns.push(columnsDataM[0]);
    // 添加 tempA 的所有元素
    newColumns = newColumns.concat(tempA);
    // 添加 columnsDataM 的剩余元素
    newColumns = newColumns.concat(columnsDataM.slice(1));
    setTempColumnsData(newColumns);
  };

  const getDataList = async () => {
    if (tableLoading) return;
    setTableLoading(true);
    // devGridRef?.current?.instance.beginCustomLoading();
    let JC = selectTreeNode.JC
    if (selectTreeNode?.ZWType === 0) {
      if (selectTreeNode.IsEnd && selectTreeNode.isLeaf) {
        JC = selectTreeNode.JC
      } else {
        JC = Number(selectTreeNode.JC) + 1
      }
    }
    // 辅助账
    if (selectTreeNode?.ZWType === 1) {
      if (selectTreeNode.IsEnd) {
        JC = selectTreeNode.JC - 1
      } else {
        JC = selectTreeNode.JC
      }
    }
    try {
      const res = await getFYFXList({
        dbname,
        ROOTKMBH: selectTreeNode?.KMBH,
        KMBH: selectTreeNode?.ID,
        Data_ID: selDefaultValue,
        startTime: selMonthDataStart,
        endTime: selMonthDataEnd,
        level: 33,
        amountField: selDataValue,
        isEnd: valueRadio === 1 ? true : false,
        JC, // ZWType为0时，是非辅助帐，为1是是辅助账。
        hiddenEmptyData, // 隐藏空数据
      });
      if (res.success) {
        setDataSourceArr(res.data);
      }
    } catch (error) {
    } finally {
      setTableLoading(false);
      // devGridRef?.current?.instance.endCustomLoading();
    }
  };

  useEffect(() => {
    changeTempColumnsData(generateMonth);
  }, [generateMonth, selDefaultValue, selMonthDataStart, selMonthDataEnd]);

  useEffect(() => {
    if (selectTreeNode?.ID) {
      console.log(selectTreeNode, '@@@');
      // changeTempColumnsData(generateMonth);
      getDataList();
    }
  }, [
    generateMonth,
    selectTreeNode,
    valueRadio,
    selDataValue,
    selDefaultValue,
    selMonthDataStart,
    selMonthDataEnd,
    hiddenEmptyData
  ]);

  const onChangeDefaultNot = (e: any) => {
    setValueCheckbox(e.target.checked);
  };

  const handleMenuClick = (e: any) => {
    console.log('click', e);
  };
  const items = [
    {
      label: 'test1',
      key: '1',
      icon: <UserOutlined />,
    },
    {
      label: 'test2',
      key: '2',
      icon: <UserOutlined />,
    },
    {
      label: 'test3',
      key: '3',
      icon: <UserOutlined />,
    },
  ];

  const menuProps: any = {
    items,
    onClick: handleMenuClick,
  };

  const handleRowDblClick = (e: any) => {
    const { rowType, data, column } = e;
    const yearID = selDefaultValue;
    msgInfo(`正在打开 明细项目页面,请稍候...`);
    // UserCode={1} UserPwd={c4ca4238a0b923820dcc509a6f75849b} ProjectCode={202202-AUD-2020-001} ZcbfID={202202-AUD-2020-001}
    if (window.electronComponents) {
      const sessionParams = JSON.parse(window.sessionStorage.electronParams);
      const { sjxmbh, ZcbfID } = sessionParams.params;
      window.location.href = `cpas://OpenLocalFile/?fileName={UFCPAS4_PATH}/UFCPAS4.exe&params=UserCode={UserCode} UserPwd={UserPwd} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID} Functions=FM_103 FunParameters="Data_ID=${yearID},KMBH=${data.KMBH}"`;
    } else {
      console.error('window["electronComponents"] false');
    }
  };

  return (
    <div className="detailsTableComponent">
      {/* <div className="headerComponent"> */}
      {/* <div className="leftComponent"> */}
      {/* <Dropdown menu={menuProps} trigger={['click']}>
                    <Button type="primary">
                        相关功能
                    </Button>
                </Dropdown> */}
      {/* </div> */}
      {/* <div className="rightComponent"> */}
      {/* <Checkbox onChange={onChangeDefaultNot} checked={valueCheckbox}>
            默认无数据不显示
          </Checkbox> */}
      {/* </div> */}
      {/* </div> */}
      {/* <div className="titleHeaderComponent">
        <div className="titleTextComponent">{selectTreeNode?.KMMC}--按月分析表</div>
        <div className="titleComponent">
          <div className="leftComponent">被审计单位：{zcbfName}</div>
          <div className="rightComponent">
            期间：
            {selMonthDataStart && selMonthDataEnd ? `${selMonthDataStart}-${selMonthDataEnd}` : ''}
          </div>
        </div>
      </div> */}

      <TableLoading loading={tableLoading} />
      {useMemo(() => {
        return (
          <div className="tableComponent">
            <DevGrid.RangeTap
              className={` PaperDevSortableGrid devHeadersCenter  tableComponentSummary`}
              key={devBox}
              height={'100%'}
              width="100%"
              ref={devGridRef}
              dataSource={dataSourceArr}
              keyExpr="ID"
              // defaultColumns={tempColumnsData}
              columns={tempColumnsData}
              showBorders={true}
              showRowLines={true}
              showColumnLines={true}
              allowColumnResizing={true}
              searchPanel={{
                visible: false,
                width: 180,
                placeholder: '',
              }}
              onRowDblClick={handleRowDblClick}
              paging={{
                enabled: false,
              }}
              loadPanel={{ enabled: false }}
              scrolling={{
                // mode: 'virtual',
                // rowRenderingMode: 'virtual',
              }}
              onCellDblClick={(e) => {
                const { rowType, data, column } = e;
                console.log('@@@', data);
              }}
              columnMinWidth={50}
              sheetName={`${selectTreeNode.name}-${selDefaultValue}按月分析`}
              excelName={`${selectTreeNode.name}-${selDefaultValue}按月分析`}
            >
              {/* <Selection mode="single" /> */}

              <Summary>
                <TotalItem
                  column="KMMC"
                  customizeText={(itemInfo: any) => {
                    return '合计：' + dataSourceArr.length || '';
                  }}
                />
                {selArrData.map((item: any) => {
                  return (
                    <TotalItem
                      column={`${item >= 10 ? '' : '0'}${item}`}
                      summaryType="sum"
                      customizeText={(itemInfo: any) => {
                        return itemInfo.value ? moneyFormatCol(itemInfo.value) : '';
                      }}
                    />
                  );
                })}
                <TotalItem
                  column={`HJ`}
                  summaryType="sum"
                  customizeText={(itemInfo: any) => {
                    return itemInfo.value ? moneyFormatCol(itemInfo.value) : '';
                  }}
                />
              </Summary>
            </DevGrid.RangeTap>
          </div>
        );
      }, [tempColumnsData, selArrData, dataSourceArr, selectTreeNode, selDefaultValue, devBox])}
    </div>
  );
});

export default DetailsTableComponent;
